package mysql

import (
	"bluebell_qimi/models"
	"crypto/md5"
	"errors"
	"go.uber.org/zap"
	"gorm.io/gorm"

	//"database/sql"
	"encoding/hex"
)

// 把每一步数据库操作封装成函数
// 待logic层根据业务需求调用
const secret = "liwenzhou.com"

// 检查指定用户名的用户是否存在
//1. sqlx形式
/*func CheckUserExist(username string) (err error) {
	sqlStr := `select count(user_id) from user where username=?`
	var count int
	if err := db.Get(&count, sqlStr, username); err != nil {
		return err
	}
	if count > 0 {
		return ErrorUserExist
	}
	return
}*/
//2. gorm形式
func CheckUserExist(username string) error {
	user := &models.User{}
	result := db.First(&user, "username=?", username)

	if result.Error == gorm.ErrRecordNotFound {
		return nil //用户不存在，返回nil
	}
	if result.Error != nil {
		return result.Error
	}

	//如果没有错误，至少找到一条记录
	return ErrorUserExist
}

// InsertUser 向数据库中插入一条新的用户记录
//1. sqlx形式
/*func InsertUser(user *models.User) (err error) {
	//对密码进行加密
	user.Password = encyptPassword(user.Password)
	//执行SQL入库
	sqlStr := "insert into user(user_id,username,password) values(?,?,?)"
	_, err = db.Exec(sqlStr, user.UserID, user.Username, user.Password)
	return
}*/
//2. gorm形式
func InsertUser(user *models.User) (err error) {
	//db.AutoMigrate(&models.User{})
	//对密码进行加密
	user.Password = encyptPassword(user.Password)
	result := db.Omit("Token").Create(&user)
	return result.Error
}

// 密码加密
func encyptPassword(oPasswordd string) string {
	h := md5.New()
	h.Write([]byte(secret))
	return hex.EncodeToString(h.Sum([]byte(oPasswordd)))
}

// 登录
//1. sqlx形式
/*func Login(user *models.User) (err error) {
	//保存原始密码,用户登录的密码
	oPassword := user.Password
	sqlStr := `select user_id,username,password from user where username=? `
	//user是指针，根据查询到的内容，user会更新
	err = db.Get(user, sqlStr, user.Username)
	if err == sql.ErrNoRows {
		return ErrorUserNotExist
	}
	if err != nil {
		//查询数据库失败
		return err
	}
	//判断密码是否正确
	password := encyptPassword(oPassword)

	if password != user.Password {
		return ErrorInvalidPassword
	}
	return
}*/
//2. gorm形式
func Login(user *models.User) (err error) {
	//保存原始密码，用户登录的密码
	oPassword := user.Password
	if err := db.Where("username = ?", user.Username).First(&user).Error; err != nil {
		return ErrorUserNotExist
	}
	//判断密码是否正确
	password := encyptPassword(oPassword)
	if password != user.Password {
		return ErrorInvalidPassword
	}
	return
}

// 根据id查询用户信息
//1. sqlx版
/*func GetUserById(uid int64) (user *models.User, err error) {
	user = new(models.User)
	sqlStr := `select user_id,username from user where user_id=?`
	err = db.Get(user, sqlStr, uid)
	return
}*/

// 2. gorm版
func GetUserById(uid int64) (user *models.User, err error) {
	user = new(models.User)
	if err = db.Where("user_id=?", uid).First(&user).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			zap.L().Warn("user not found")
			err = nil
		}
	}
	return
}
